package com.nh.actionTerminal;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.ServletActionContext;
import org.hibernate.Criteria;
import org.hibernate.Query;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.nh.entity.BaseEntity;
import com.nh.service.IBaseService;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;

@SuppressWarnings("serial")
@Controller
@Scope("prototype")
public class GKLTerminalBaseAction extends ActionSupport {

	private IBaseService baseService;

	public Criteria createCriteria(Class<? extends BaseEntity> clazz) {
		return this.baseService.getBaseDao().getSession().createCriteria(clazz);
	}

	public Query createQuery(String hql) {
		return this.baseService.getBaseDao().getSession().createQuery(hql);
	}

	public IBaseService getBaseService() {
		return baseService;
	}
	/**
	 * 得到绝对路径（D:/tomcat/ng/）
	 * 
	 * @return
	 */
	public String getSavePath() {
		String serverPath = ServletActionContext.getServletContext().getRealPath(File.separator);
		serverPath = serverPath.replaceAll("\\\\", "/");
		return serverPath;
	}
	/**
	 * 得到当前工程路径URL(http://localhost:8080/ng)
	 * 
	 * @return
	 */
	public String getProjectURL() {
		ActionContext context = ActionContext.getContext();
		HttpServletRequest request = (HttpServletRequest) context.get(ServletActionContext.HTTP_REQUEST);
		String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort()+"/"+request.getContextPath();
		return basePath;
		// return "http://192.168.1.101:8080";
	}
	public String getProjectPath() {
		ActionContext context = ActionContext.getContext();
		HttpServletRequest request = (HttpServletRequest) context.get(ServletActionContext.HTTP_REQUEST);
		String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort();
		return basePath;
		// return "http://192.168.1.101:8080";
	}
	/**
	 * 得到工程名
	 * @return
	 */
	public String getProjectName(){
		ActionContext context = ActionContext.getContext();
		HttpServletRequest request = (HttpServletRequest) context.get(ServletActionContext.HTTP_REQUEST);
		return request.getContextPath();
		
	}

	@Resource
	public void setBaseService(IBaseService baseService) {
		this.baseService = baseService;
	}
	public boolean writResponse(String JSONString) {
		HttpServletResponse resp = ServletActionContext.getResponse();
		resp.setCharacterEncoding("utf-8");
		resp.setContentType("text/html; charset=utf-8");
		PrintWriter out = null;
		try {
			out = resp.getWriter();

			out.write(JSONString);
		} catch (IOException e) {
			e.printStackTrace();
			return false;
		} finally {
			if (out != null) {
				out.close();
			}
		}
		return true;
	}
}
